<template>
  <div class="course-video-container">
    <el-card>
      <div slot="header">视频上传</div>
      <el-form label-width="80px">
        <el-form-item label="课程">
          <el-input disabled></el-input>
        </el-form-item>
        <el-form-item label="课时">
          <el-input disabled></el-input>
        </el-form-item>
        <el-form-item label="视频上传">
          <input ref="video" type="file" />
        </el-form-item>
        <el-form-item label="封面上传">
          <input ref="image" type="file" />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="handleUpload"
          >开始上传</el-button>
          <el-button @click="$router.back()">返回</el-button>
        </el-form-item>
        <el-form-item>
          <p v-if="isStartUpload">视频上传中: {{ uploadPercent }}%</p>
          <p v-if="isUploadSuccess">视频转码中：{{ isTransCodeSuccess ? '完成' : '：正在处理，请稍等...' }}</p>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import {
  getAliyunImagUploadAddressAdnAuth,
  getAliyunVideoUploadAddressAdnAuth,
  aliyunTransCode,
  getAliyunTransCodePercent
} from '@/services/aliyun-upload'

export default Vue.extend({
  name: 'CoursevideoIndex',
  props: {
    courseId: {
      type: [String, Number],
      required: true,
      default: ''
    }
  },
  data () {
    return {
      uploader: null,
      imageUrl: '',
      videoId: '',
      uploadPercent: 0,
      isUploadSuccess: false,
      isTransCodeSuccess: false,
      isStartUpload: false
    }
  },
  created () {
    ;(this as any).initUploader()
  },
  computed: {
    video () {
      return (this.$refs as any).video
    },
    image () {
      return (this.$refs as any).image
    }
  },
  methods: {
    initUploader () {
      (this as any).uploader = new window.AliyunUpload.Vod({
        // 阿里账号ID，必须有值
        userId: '1618139964448548',
        // 上传到视频点播的地域，默认值为'cn-shanghai'，//eu-central-1，ap-southeast-1
        region: '',
        // 分片大小默认1 MB，不能小于100 KB
        partSize: 1048576,
        // 并行上传分片个数，默认5
        parallel: 5,
        // 网络原因失败时，重新上传次数，默认为3
        retryCount: 3,
        // 网络原因失败时，重新上传间隔时间，默认为2秒
        retryDuration: 2,
        // 开始上传
        onUploadstarted: async (uploadInfo: any) => {
          // 1. 通过后端获取文件上传凭证
          let uploadAddressAuth
          if (uploadInfo.isImage) {
            // 获取图片上传凭证
            const { data } = await getAliyunImagUploadAddressAdnAuth()
            uploadAddressAuth = data.data
            ;(this as any).imageUrl = data.data.imageURL
          } else {
            // 获取视频上传凭证
            const { data } = await getAliyunVideoUploadAddressAdnAuth({
              fileName: uploadInfo.file.name,
              imageUrl: (this as any).imageUrl // 确保先上传图片
            })
            uploadAddressAuth = data.data
            ;(this as any).videoId = uploadAddressAuth.videoId
          }
          // 2. 调用 setUploadAuthAndAddress 设置上传凭证
          ;(this as any).uploader.setUploadAuthAndAddress(
            uploadInfo,
            uploadAddressAuth.uploadAuth,
            uploadAddressAuth.uploadAddress,
            uploadAddressAuth.imageId || uploadAddressAuth.videoId
          )
          //  uploader.setUploadAuthAndAddress(uploadInfo,uploadAuth, uploadAddress, videoId);
          // 3. 上传进度开始
        },
        // 文件上传成功
        onUploadSucceed: function (uploadInfo: any) {
          console.log(uploadInfo)
        },
        // 文件上传失败
        onUploadFailed: function (uploadInfo: any, code: any, message: any) {
          console.log(uploadInfo, code, message)
        },
        // 文件上传进度，单位：字节
        onUploadProgress: (uploadInfo: any, totalSize: any, loadedPercent: any) => {
          console.log(uploadInfo, totalSize, loadedPercent)
          if (!uploadInfo.isImage) {
            ;(this as any).uploadPercent = Math.floor(loadedPercent * 100)
          }
        },
        // 上传凭证超时
        onUploadTokenExpired: function (uploadInfo: any) {
          console.log(uploadInfo)
        },
        // 全部文件上传结束
        onUploadEnd: async () => {
          const that = this as any
          that.isUploadSuccess = true
          // 转码请求
          await aliyunTransCode({
            lessonId: that.$route.query.lessonId,
            coverImageUrl: that.imageUrl,
            fileName: that.video.files[0].name,
            fileId: that.videoId
          })

          // 获取转码进度
          const timer = setInterval(async () => {
            const { data } = await getAliyunTransCodePercent(that.$route.query.lessonId)
            if (data.data === 100) {
              that.isTransCodeSuccess = true
              window.clearInterval(timer)
              console.log('转码成功')
            }
          }, 3000)
        }
      })
    },
    handleUpload () {
      // 初始化上传状态
      ;(this as any).isStartUpload = true
      ;(this as any).uploadPercent = 0
      ;(this as any).isUploadSuccess = false
      ;(this as any).isTransCodeSuccess = false
      // 获取上传的文件
      const videoFile = (this as any).video.files[0]
      const imageFile = (this as any).image.files[0]
      const uploader = (this as any).uploader
      // 将所选文件添加到上传列表中
      uploader.addFile(videoFile, null, null, null, '{"Vod": {}}')
      uploader.addFile(imageFile, null, null, null, '{"Vod": {}}')
      // 开始上传 触发 onUploadstarted 事件
      uploader.startUpload()
    }
  }
})
</script>

<style lang="scss" scoped>
</style>
